package com.xuelang.pipeline.app.pipeline.job;

import com.xuelang.hiforce.base.tracing.TracingConstants;
import com.xuelang.hiforce.base.utils.bean.SpringApplicationContextHolder;
import com.xuelang.pipeline.app.msg.MsgUserMessagesService;
import com.xuelang.pipeline.app.pipeline.PipelineService;
import com.xuelang.pipeline.client.msg.MsgConstant;
import com.xuelang.pipeline.client.msg.UserMessageSaveDTO;
import com.xuelang.pipeline.client.pipeline.dto.TriggerPipelineDTO;
import com.xuelang.pipeline.client.pipeline.enums.TriggerWayEnum;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.MDC;

import java.util.Collections;

/**
 * <p>流水线定时任务</p>
 *
 * @author : yixin.lys
 * @date : 2024-06-11 17:24
 **/
@Slf4j
public class PipelineJob implements Job {

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
        String pipelineCode = jobDataMap.getString("pipelineCode");
        Integer triggerWay = jobDataMap.getIntValue("triggerWay");
        String userId = jobDataMap.getString("userId");
        MDC.put(TracingConstants.USER_ID, userId);
        log.info("Executing job with pipeline code: " + pipelineCode);
        log.info("Executing job with trigger type: " + TriggerWayEnum.fromValue(triggerWay));
        // 定时触发时记录消息
        MsgUserMessagesService msgUserMessagesService = SpringApplicationContextHolder.getSpringBean(MsgUserMessagesService.class);
        UserMessageSaveDTO userMessageSaveDTO = new UserMessageSaveDTO();
        userMessageSaveDTO.setMsgType(MsgConstant.MSG_TYPE_TEXT);
        userMessageSaveDTO.setTitle("定时任务触发");
        userMessageSaveDTO.setContent("流水线编码为：" + pipelineCode + " 的定时任务已经触发。");
        userMessageSaveDTO.setReceiveUserIds(Collections.singletonList(userId));
        msgUserMessagesService.saveMessage(userMessageSaveDTO);
        // 触发对应流水线
        PipelineService pipelineService = SpringApplicationContextHolder.getSpringBean(PipelineService.class);
        TriggerPipelineDTO reqDTO = TriggerPipelineDTO.builder().pipelineCode(pipelineCode).triggerType(triggerWay).build();
        pipelineService.triggerPipelineInstance(reqDTO);
        MDC.clear();
    }

}
